package com.kuang.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * Author: Zhang Dongwei
 * Date: 2022/3/16 14:35
 */
public class Test {
    private static final long SUM = 10_0000_0000;

    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        test1();
//        test2();
        test3();
    }
    /*
     * 使用普通方法
     *
     * */
    public static void test1(){
        long start = System.currentTimeMillis();
        long sum = 0L;
        for (Long i = 1L; i <= SUM; i++) {
            sum+=i;
        }
        long end = System.currentTimeMillis();
        System.out.println(sum);
        System.out.println("时间：" + (end-start)); // 2221
        System.out.println("---------------");
    }

    /*
     *
     * 使用 ForkJoin 方法
     * */
    public static void test2() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinDemo(0L,10_0000_0000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);// 提交任务

        Long along = submit.get();

        System.out.println(along);
        long end = System.currentTimeMillis();
        System.out.println("时间：" + (end - start));
        System.out.println("---------------");
    }

    /*
     * 使用流计算
     * */
    public static void test3(){
        long star = System.currentTimeMillis();

        long sum = LongStream.range(0L,10_0000_0000L).parallel().reduce(0,Long::sum);
        System.out.println(sum);
        long end = System.currentTimeMillis();
        System.out.println("时间：" + (end - star));
    }
}
